<!-- 想定 -->
<script lang="ts" setup>
import type { ScnTableInfo, TableRequestData } from "@@/apis/scn/type"
import type { FormInstance } from "element-plus"
import { deleteMulScenario, exportScnApi, publishApi, searchScenarioListApi } from "@/common/apis/scn"
import { usePagination } from "@/common/composables/usePagination"
import { FormTypeEnum } from "@/common/constants/other-keys"
import { getProjectId } from "@/common/utils/cache/local-storage"
import { downloadFile } from "@/common/utils/fileUtils"
import Card from "@@/components/CardItem/card.vue"
import { Search } from "@element-plus/icons-vue"
import XEUtils from "xe-utils"
import CreateOrUpdate from "./components/create-or-update.vue"
import ImportFromResource from "./components/import-from-resource.vue"
import SaveAs from "./components/save-as.vue"
import Upload from "./components/upload.vue"

defineOptions({
  // 命名当前组件
  name: "ScnIndex"
})

const router = useRouter()
const isGrid = ref<boolean>(true)
const searchFormRef = ref<FormInstance | null>(null)
const searchKey = ref()
const loading = ref<boolean>(false)
const tableData = ref<ScnTableInfo[]>([])
const multipleSelection = ref<ScnTableInfo[]>([])
const dialogType = ref<FormTypeEnum>(FormTypeEnum.VIEW)
const dialogVisible = ref<boolean>(false)
const curId = ref<string>()
const TableRef = ref()
const editDialogRef = ref()
const dialogVisibleUpload = ref<boolean>(false)
const dialogVisibleImport = ref<boolean>(false)
const saveAsVisible = ref<boolean>(false)
const { paginationData, handleSizeChange, handleCurrentChange } = usePagination()
import { useAutoRefresh } from "@/layouts/composables/useAutoRefresh"

function resetSearch() {
  searchFormRef.value?.resetFields()
  handleSearch()
}

function getTableData() {
  loading.value = true
  const params: TableRequestData = {
    pageSize: paginationData.pageSize,
    current: paginationData.currentPage,
    searchKey: searchKey.value,
    ...(getProjectId() ? { pId: getProjectId() } : {})
  }
  searchScenarioListApi(params)
    .then(({ data }) => {
      tableData.value = data.rows
      paginationData.total = data.total
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}

function handleSearch() {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}

function handleCreate() {
  nextTick(() => {
    curId.value = undefined
    dialogType.value = FormTypeEnum.CREATE
    dialogVisible.value = true
  })
}

function handleSelectionChange(val: ScnTableInfo[]) {
  multipleSelection.value = val
}
function handleMultipleDelete() {
  const ids: string[] = []
  const names: string[] = []
  multipleSelection.value.forEach((item) => {
    ids.push(item.id)
    names.push(item.scnName)
  })
  ElMessageBox.confirm(`正在删除想定：${names.join("，")}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteMulScenario(ids).then(() => {
      ElMessage.success("删除成功")
      hanldeClearSelection()
      getTableData()
    })
  })
}
function hanldeClearSelection() {
  nextTick(() => {
    TableRef.value.clearSelection()
  })
}
function getRowKeys(row: ScnTableInfo) {
  return row.id
}
function closeDialog(param: string | undefined) {
  dialogVisible.value = false
  curId.value = undefined
  TableRef.value!.setCurrentRow(null)
  if (param && param === "refresh") getTableData()
}
// #region 下载想定
function handleDownload(row: ScnTableInfo) {
  exportScnApi(row.id).then((res) => {
    downloadFile(res)
  })
}
// #endregion
// #region 删
function handleDelete(row: ScnTableInfo) {
  ElMessageBox.confirm(`正在删除想定：${row.scnName}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteMulScenario([row.id]).then(() => {
      ElMessage.success("删除成功")
      hanldeClearSelection()
      getTableData()
    })
  })
}
// #endregion
function handleToggleSelect(row: ScnTableInfo) {
  TableRef.value!.toggleRowSelection(row, undefined, false)
}
// #region 另存为
function handleSaveAs(row: ScnTableInfo) {
  curId.value = row.id
  saveAsVisible.value = true
}
function handleSaveAsClose(param: string | undefined) {
  saveAsVisible.value = false
  curId.value = undefined
  TableRef.value!.setCurrentRow(null)
  if (param && param === "refresh") getTableData()
}
// #endregion
// #region 本地上传
function handleUploadCreate() {
  nextTick(() => {
    dialogVisibleUpload.value = true
  })
}
function closeDialogUpload(param: string | undefined) {
  dialogVisibleUpload.value = false
  TableRef.value!.setCurrentRow(null)
  if (param && param === "refresh") getTableData()
}
// #endregion
// #region 从资源库导入
function handleImportCreate() {
  nextTick(() => {
    dialogVisibleImport.value = true
  })
}
function closeDialogImport(param: string | undefined) {
  dialogVisibleImport.value = false
  TableRef.value!.setCurrentRow(null)
  if (param && param === "refresh") getTableData()
}
// #endregion

function handleView(row: ScnTableInfo) {
  if (getProjectId()) {
    router.replace({ name: "MyProjectScnView", query: { id: row.id } })
  } else {
    router.replace({ name: "ScnView", query: { id: row.id } })
  }
}

function handlePublish(row: ScnTableInfo) {
  publishApi({ id: row.id }).then(() => {
    ElMessage.success("发布成功")
  })
}
useAutoRefresh(getTableData)
/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })

const selectedId = computed(() => {
  if (multipleSelection.value !== undefined && multipleSelection.value.length > 0) {
    const ids = XEUtils.map(multipleSelection.value, (item) => {
      return item.id
    })
    return ids
  }
  return []
})
</script>

<template>
  <div class="app-container pager-container">
    <div class="cc-search">
      <div class="cc-search-common">
        <el-input v-model="searchKey" size="large" placeholder="请输入搜索内容" class="csc-search-input" @keydown.enter="handleSearch">
          <template #append>
            <el-button :icon="Search" v-throttle="() => handleSearch()" />
          </template>
        </el-input>
      </div>
    </div>

    <div v-loading="loading" class="content-other">
      <div class="flex-between mb-main-padding">
        <div class="flex-y-center tag">
          <el-button v-if="getProjectId() != null" type="primary" @click="handleCreate">
            新建
          </el-button>
          <el-button v-if="getProjectId() != null" type="primary" @click="handleImportCreate">
            导入
          </el-button>
          <el-button v-if="getProjectId() != null" type="primary" @click="handleUploadCreate">
            本地上传
          </el-button>
          <el-button
            :disabled="multipleSelection.length < 1" type="danger"
            @click="handleMultipleDelete"
          >
            批量删除
          </el-button>
        </div>
        <div class="flex-y-center sh-operate">
          <div class="sh-btn" :class="{ active: isGrid }" @click="() => isGrid = true">
            <el-tooltip content="卡片" placement="bottom">
              <SvgIcon name="table-grid" />
            </el-tooltip>
          </div>
          <div class="sh-btn" :class="{ active: !isGrid }" @click="() => isGrid = false">
            <el-tooltip content="列表" placement="bottom">
              <SvgIcon name="table-list" />
            </el-tooltip>
          </div>
        </div>
      </div>
      <div v-show="isGrid" class="cpi-content-main">
        <div class="custom-card-container">
          <template v-for="(item, index) in tableData" :key="index">
            <Card
              tag=""
              :name="item.scnName"
              :description="(item.description as string)"
              :create-by="item.scnName"
              :show-name="false"
              :create-time="item.createTime"
              :data="item"
              :selected="selectedId.includes(item.id as string)"
              :is-save-as="getProjectId() != null"
              :is-publish="getProjectId() != null"
              :is-other="true"
              :show-tag="false"
              @handle-view="handleView"
              @handle-delete="handleDelete"
              @handle-download="handleDownload"
              @handle-save-as="handleSaveAs"
              @handle-publish="handlePublish"
              @toggle-select="handleToggleSelect"
            />
          </template>
        </div>
      </div>
      <div v-show="!isGrid" class="cpi-content-main">
        <el-auto-resizer>
          <template #default="{ height, width }">
            <el-table
              ref="TableRef" v-loading="loading" :data="tableData" :row-key="getRowKeys" :width="width"
              :height="height" @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" :reserve-selection="true" width="55" />
              <el-table-column prop="scnName" show-overflow-tooltip label="名称" />
              <el-table-column prop="scnStartTime" label="仿真开始时间" />
              <el-table-column prop="scnEndTime" show-overflow-tooltip label="仿真结束时间" />
              <el-table-column prop="description" show-overflow-tooltip label="描述" />
              <el-table-column label="操作" align="center" width="180">
                <template #default="scope">
                  <el-space :size="12">
                    <el-link :underline="false" @click.stop v-throttle="() => handleView(scope.row)" title="查看">
                      <el-icon :size="18">
                        <View />
                      </el-icon>
                    </el-link>
                    <el-link :underline="false" @click.stop v-throttle="() => handleDownload(scope.row)" title="下载">
                      <el-icon :size="18">
                        <Download />
                      </el-icon>
                    </el-link>
                    <el-link
                      v-if="getProjectId() != null" :underline="false" @click.stop="handleSaveAs(scope.row)"
                      title="另存为"
                    >
                      <el-icon :size="18">
                        <DocumentAdd />
                      </el-icon>
                    </el-link>
                    <el-link
                      v-if="getProjectId() != null" :underline="false" @click.stop="handlePublish(scope.row)"
                      title="发布"
                    >
                      <el-icon :size="18">
                        <Position />
                      </el-icon>
                    </el-link>
                    <el-link :underline="false" type="danger" @click.stop v-throttle="() => handleDelete(scope.row)" title="删除">
                      <el-icon :size="18">
                        <Delete />
                      </el-icon>
                    </el-link>
                  </el-space>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-auto-resizer>
      </div>
    </div>

    <div class="pager-wrapper">
      <el-pagination
        background
        layout="total, sizes, ->, prev, pager, next, jumper"
        :disabled="loading"
        :page-sizes="paginationData.pageSizes"
        :total="paginationData.total"
        :page-size="paginationData.pageSize"
        :current-page="paginationData.currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <Upload :visible="dialogVisibleUpload" @close-dialog="closeDialogUpload" />
    <CreateOrUpdate
      ref="editDialogRef" :id="curId" :dialog-type="dialogType" :visible="dialogVisible"
      @close-dialog="closeDialog"
    />
    <ImportFromResource :visible="dialogVisibleImport" @close-dialog="closeDialogImport" />
    <SaveAs :id="curId" :visible="saveAsVisible" @close-dialog="handleSaveAsClose" />
  </div>
</template>
